// review.js - 订单评价页面逻辑

Page({
  data: {
    orderId: '',
    goodsList: [],
    overallRating: 5, // 默认5星
    content: '',
    images: [],
    anonymous: false,
    loading: true
  },

  onLoad: function(options) {
    // 获取订单ID
    if (options.id) {
      this.setData({
        orderId: options.id
      });
      this.loadOrderGoods();
    } else {
      wx.showToast({
        title: '订单ID不存在',
        icon: 'none',
        duration: 2000,
        complete: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 2000);
        }
      });
    }
  },

  // 加载订单商品列表
  loadOrderGoods: function() {
    this.setData({ loading: true });
    
    // 模拟请求，实际应调用后端API
    wx.request({
      url: 'https://api.example.com/orders/' + this.data.orderId + '/goods',
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.code === 0) {
          let goodsList = res.data.data;
          // 为每个商品添加默认评分
          goodsList = goodsList.map(item => ({
            ...item,
            rating: 5 // 默认5星
          }));
          
          this.setData({
            goodsList: goodsList
          });
        } else {
          wx.showToast({
            title: '商品信息加载失败',
            icon: 'none'
          });
          console.error('加载商品信息失败:', res);
        }
      },
      fail: (err) => {
        // 模拟数据，用于开发测试
        const mockGoodsList = this.getMockGoodsList();
        this.setData({
          goodsList: mockGoodsList
        });
        console.error('请求失败，使用模拟数据:', err);
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  // 模拟商品列表数据
  getMockGoodsList: function() {
    return [
      {
        id: 'g001',
        name: '高级运动鞋 舒适透气 减震耐磨',
        spec: '黑色 42码',
        image: 'https://example.com/images/goods1.jpg',
        rating: 5
      }
    ];
  },

  // 设置总体评分
  setOverallRating: function(e) {
    const rating = e.target.dataset.rating;
    this.setData({
      overallRating: rating
    });
  },

  // 设置单个商品评分
  setGoodsRating: function(e) {
    const index = e.currentTarget.dataset.index;
    const rating = e.target.dataset.rating;
    
    const goodsList = [...this.data.goodsList];
    goodsList[index].rating = rating;
    
    this.setData({
      goodsList: goodsList
    });
  },

  // 评价内容输入
  onContentInput: function(e) {
    this.setData({
      content: e.detail.value
    });
  },

  // 上传图片
  uploadImage: function() {
    const that = this;
    
    wx.chooseImage({
      count: 9 - that.data.images.length, // 最多9张
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // 显示上传中提示
        wx.showLoading({
          title: '上传中...',
        });
        
        const tempFilePaths = res.tempFilePaths;
        const uploadTasks = tempFilePaths.map(tempFilePath => {
          return new Promise((resolve, reject) => {
            // 模拟上传，实际应调用上传API
            setTimeout(() => {
              // 假设上传成功后返回的图片URL
              const imageUrl = 'https://example.com/uploads/' + Date.now() + '.jpg';
              resolve(imageUrl);
            }, 1000);
          });
        });
        
        Promise.all(uploadTasks).then(imageUrls => {
          const images = [...that.data.images, ...imageUrls];
          that.setData({
            images: images
          });
          
          wx.hideLoading();
        }).catch(err => {
          wx.hideLoading();
          wx.showToast({
            title: '图片上传失败',
            icon: 'none'
          });
          console.error('图片上传失败:', err);
        });
      }
    });
  },

  // 删除图片
  deleteImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.images];
    images.splice(index, 1);
    
    this.setData({
      images: images
    });
  },

  // 切换匿名评价
  toggleAnonymous: function() {
    this.setData({
      anonymous: !this.data.anonymous
    });
  },

  // 提交评价
  submitReview: function() {
    // 表单验证
    if (!this.data.content.trim()) {
      wx.showToast({
        title: '请输入评价内容',
        icon: 'none'
      });
      return;
    }
    
    // 显示提交中提示
    wx.showLoading({
      title: '提交中...',
    });
    
    // 构建评价数据
    const reviewData = {
      order_id: this.data.orderId,
      overall_rating: this.data.overallRating,
      content: this.data.content,
      images: this.data.images,
      anonymous: this.data.anonymous,
      goods_ratings: this.data.goodsList.map(item => ({
        goods_id: item.id,
        rating: item.rating
      }))
    };
    
    // 模拟提交评价，实际应调用后端API
    wx.request({
      url: 'https://api.example.com/orders/' + this.data.orderId + '/review',
      method: 'POST',
      data: reviewData,
      success: (res) => {
        if (res.data && res.data.code === 0) {
          wx.hideLoading();
          wx.showToast({
            title: '评价成功',
            icon: 'success',
            complete: () => {
              setTimeout(() => {
                wx.navigateBack();
              }, 1500);
            }
          });
        } else {
          wx.hideLoading();
          wx.showToast({
            title: '评价失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        });
        console.error('提交评价失败:', err);
      }
    });
  }
});